<script setup lang="ts" name="StoreForm">
import { reactive, ref, getCurrentInstance } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import {
  addStoreApi,
  getGroupTreeApi,
  getStoreDetailApi,
  getStoreAllApi,
  updateStoreApi,
} from "@/addon/htscrm/api";
import { getUserList } from '@/app/api/user'
import { cloneDeep } from "lodash-es";
import { t } from "@/lang";

const defaultFormData: IStoreItem = {
  id: 0,
  title: "",
  account: "",
  password: "",
  store_id: 0,
  group_id: 0,
  mobile: "",
  address: "",
  lat: "",
  lng: "",
  kefu_image: "",
  auto_pass_staus: 0,
};

const instance = getCurrentInstance() as any
const { $convert } = instance?.appContext.config.globalProperties

/** 表单实例 */
const formRef = ref<FormInstance>();
/** 表单数据 */
const formData = ref<IStoreItem>({ ...defaultFormData });

// 表单规则
const formRules = reactive<FormRules>({
  title: [
    { required: true, message: t("form.title.placeholder"), trigger: "blur" },
  ],
  account: [
    { required: true, message: t("form.account.placeholder"), trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value!.length < 6) {
          return callback(new Error("账号不能少于6位!"));
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: t("form.password.placeholder"),
      trigger: "blur",
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value!.length < 6) {
          return callback(new Error("密码不能少于6位!"));
        }
        if (
          formData.value.confirm_password &&
          value !== formData.value.confirm_password
        ) {
          return callback(new Error(t("form.confirmPasswordError")));
        }
        formRef.value?.validateField("confirm_password");
        return callback();
      },
      trigger: "blur",
    },
  ],
  confirm_password: [
    {
      required: true,
      message: t("form.confirm_password.placeholder"),
      trigger: "blur",
    },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value!.length < 6) {
          return callback(new Error("密码不能少于6位!"));
        }
        if (formData.value.password && value !== formData.value.password) {
          return callback(new Error(t("form.confirmPasswordError")));
        }

        formRef.value?.validateField("password");
        return callback();
      },
      trigger: "blur",
    },
  ],
});

const storeList = ref<Partial<IStoreItem>[]>([]);
const groupList = ref<IGroupItem[]>([]);

/**
 * @description 初始化
 */
function init(row?: IStoreItem) {
  formRef.value?.resetFields();
  if (row?.id) {
    getDetail(row.id);
  } else {
    formData.value = { 
      ...defaultFormData,
      group_id: row?.group_id || 0,
    };
  }

  getStoreList();
  getGroupList();
  loadUserList()
}

async function getDetail(id: IStoreItem["id"]) {
  const res = await getStoreDetailApi(id);
  formData.value = res.data;
  formData.value.auto_pass_staus = res.data.auto_pass_staus || 0;
}

/**
 * @description 获取分组列表
 */
async function getGroupList() {
  const res = await getGroupTreeApi();
  groupList.value = res.data;
}

/**
 * @description 获取关联员工
 */
/**
 * 获取用户列表
 */
interface IUserItem {
  username: string;
  uid: number;
}
const userList = ref<IUserItem[]>([]);
const loadUserList = () => {

    getUserList({
        page: 1,
        limit: 100,
    }).then(res => {
      
        userList.value = res.data.data
    }).catch(() => {
       
    })
}

/**
 * @description 获取上级门店
 */
async function getStoreList() {
  const res = await getStoreAllApi();
  storeList.value = [{ id: 0, title: t("default.store.name") }, ...res.data];
}

/**
 * @description 提交保存
 */
function submit() {
  return new Promise((resolve, reject) => {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        const params = cloneDeep(formData.value);

        // 表单校验
        params.id ? await updateStoreApi(params) : await addStoreApi(params);
        ElMessage.success(t("save.success"));
        resolve(true);
      } else {
        reject(new Error(t("form.validateError")));
      }
    });
  });
}

defineExpose({
  init,
  submit,
});
</script>

<template>
  <el-form
    class="f-form"
    ref="formRef"
    label-width="120px"
    :model="formData"
    :rules="formRules">
    <el-form-item
      :label="t('form.title')"
      prop="title">
      <el-input
        v-model="formData.title"
        :placeholder="t('form.title.placeholder')" />
    </el-form-item>
    <el-form-item
      v-if="!formData.id"
      :label="t('form.account')"
      prop="account">
      <el-input
        v-model.trim="formData.account"
        :placeholder="t('form.account.placeholder')" />
    </el-form-item>
    <el-form-item
      v-if="!formData.id"
      :label="t('form.password')"
      prop="password">
      <el-input
        v-model="formData.password"
        type="password"
        :placeholder="t('form.password.placeholder')" />
    </el-form-item>
    <el-form-item
      v-if="!formData.id"
      :label="t('form.confirm_password')"
      prop="confirm_password">
      <el-input
        v-model="formData.confirm_password"
        type="password"
        :placeholder="t('form.confirm_password.placeholder')" />
    </el-form-item>
    <el-form-item :label="t('form.store_id')">
      <el-select
        v-model="formData.store_id"
        filterable
        :placeholder="t('form.store_id.placeholder')"
        class="min-w-[400px]">
        <el-option
          v-for="item in storeList"
          :key="item.id"
          :label="item.title"
          :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item :label="t('form.group_id')">
      <el-cascader
        v-model="formData.group_id"
        :options="groupList"
        :props="{
          checkStrictly: true,
          emitPath: false,
          value: 'id',
          label: 'name',
          children: 'child',
        }"
        filterable
        :placeholder="t('form.group_id.placeholder')" />
    </el-form-item>
    <el-form-item :label="t('form.work_user_id')">
      <el-select
        v-model="formData.work_user_id"
        :placeholder="t('form.work_user_id.placeholder')"
        class="min-w-[400px]">
        <el-option
          v-for="item in userList"
          :key="item.uid"
          :label="item.username"
          :value="item.uid" />
      </el-select>
    </el-form-item>
    <el-form-item :label="t('form.mobile')">
      <el-input
        v-model="formData.mobile"
        :placeholder="t('form.mobile.placeholder')" />
    </el-form-item>
    <el-form-item :label="t('form.address')">
      <el-input
        v-model="formData.address"
        class="max-w-[400px]"
        type="textarea"
        :placeholder="t('form.address.placeholder')" />
    </el-form-item>
    <el-form-item :label="t('form.review')">
       <el-radio-group v-model="formData.auto_pass_staus">
        <el-radio :value="$convert(0, formData.auto_pass_staus)">跟随系统</el-radio>
        <el-radio :value="$convert(1, formData.auto_pass_staus)">手动审核</el-radio>
        <el-radio :value="$convert(2, formData.auto_pass_staus)">自动审核</el-radio>
        <el-radio :value="$convert(3, formData.auto_pass_staus)">企微</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item :label="t('form.lat')">
      <el-input
        v-model="formData.lat"
        :placeholder="t('form.lat.placeholder')">
        <template #prepend>lat</template>
      </el-input>
      <el-input
        class="mt-[10px]"
        v-model="formData.lng"
        :placeholder="t('form.lng.placeholder')">
        <template #prepend>lng</template>
      </el-input>
    </el-form-item>
    <el-form-item :label="t('form.kefu_image')">
      <upload-image
        v-model="formData.kefu_image"
        :limit="1" />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup></script>
